package cn.yuanqiao.web.controller.archive.archiveFormSave;

import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.management.ObjectName;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.domain.TenantSysDictData;
import cn.yuanqiao.archive.appManager.domain.TenantSysDictType;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictDataService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.archiveBorrow.domain.YqDaBorrow;
import cn.yuanqiao.archive.archiveBorrow.domain.YqdaborrowItem;
import cn.yuanqiao.archive.archiveFormSave.domain.YqdaArchiveYijiaoEntity;
import cn.yuanqiao.archive.archiveFormSave.service.impl.YqdaArchiveFormServiceImpl;
import cn.yuanqiao.archive.common.util.SplitArchiveList;
import cn.yuanqiao.archive.report.service.reportService;
import cn.yuanqiao.archive.wenjianzhengli.service.impl.WenjianzhengliServiceImpl;
import cn.yuanqiao.common.annotation.Excel;
import cn.yuanqiao.common.constant.SecurityConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.entity.SysDictData;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.fastjson2.JSONObject;

import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.compress.archivers.ArchiveException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.archiveFormSave.domain.YqdaArchiveForm;
import cn.yuanqiao.archive.archiveFormSave.service.IYqdaArchiveFormService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 归档申请单Controller
 *
 * @author yuanqiao
 * @date 2023-07-26
 */
@RestController
@RequestMapping("/archive/archiveFormSave")
public class YqdaArchiveFormController extends BaseController
{
    @Autowired
    private IYqdaArchiveFormService yqdaArchiveFormService;

    @Autowired
    private ITenantCateMdataListService tenantCateMdataListService;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    @Resource
    private reportService reportService;

    @Autowired
    private ITenantSysDictTypeService sysDictTypeService;

    @Autowired
    private ITenantSysDictDataService sysDictDataService;

    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;

    @Autowired
    private SplitArchiveList splitArchiveList;
    @Autowired
    private WenjianzhengliServiceImpl wenjianzhengliService;
    @Autowired
    private YqdaArchiveFormServiceImpl yqdaArchiveFormServiceImpl;
    @Autowired
    private ITenantCategoryService iTenantCategoryService;

    /**
     * 查询归档申请单列表
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqdaArchiveForm yqdaArchiveForm)
    {
        startPage();
        List<YqdaArchiveForm> list = yqdaArchiveFormService.selectYqdaArchiveFormList(yqdaArchiveForm);
        return getDataTable(list);
    }

    /**
     * 查询归档申请单列表
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:list')")
    @GetMapping("/getArchiveList")
    public AjaxResult getArchiveList(YqdaArchiveForm yqdaArchiveForm)
    {

        List<Map<String, Object>> list = yqdaArchiveFormService.getArchiveListByArchiveCategory(yqdaArchiveForm);
        return AjaxResult.success("查询成功",list);
    }

    @PostMapping("/getArchiveTotal")
    public AjaxResult getArchiveTotal(@RequestParam("istype")String istype,@RequestParam(required = false,value = "instanceId")String instanceId)
    {
        Map<String, Object> resultMap = new HashMap<>();
        if ("1".equals(istype)){
            List<Map<String, Object>> list = yqdaArchiveFormService.getArchiveListByArchiveCategory(new YqdaArchiveForm());
            if (list!=null&&list.size()!=0){
                Map<String, Object> tempData = list.get(0);
                String daType = String.valueOf(tempData.get("DA_TYPE"));
                List<String> archiveIds = new ArrayList<>();
                list.forEach(item->archiveIds.add(String.valueOf(item.get("ID"))));
                resultMap = yqdaArchiveFormService.getArchiveTotal(daType,archiveIds);
            }else {
                resultMap.put("itemTotal",0);
                resultMap.put("folderTotal",0);
                resultMap.put("fileTotal",0);
            }
            System.out.println(111);
        }else {
            Map<String, Object> archiveTotal = remoteActivitiService.getArchiveTotal(istype, instanceId).getData();
            List<Map<String, Object>> archiveData = (List<Map<String, Object>>) archiveTotal.get("data");
            if (archiveData!=null&&archiveData.size()!=0){
                Map<String, Object> tempData = archiveData.get(0);
                String daType = String.valueOf(tempData.get("DA_TYPE"));
                List<String> archiveIds = new ArrayList<>();
                archiveData.forEach(item->archiveIds.add(String.valueOf(item.get("ID"))));
                resultMap = yqdaArchiveFormService.getArchiveTotal(daType,archiveIds);
            }else {
                resultMap.put("itemTotal",0);
                resultMap.put("folderTotal",0);
                resultMap.put("fileTotal",0);
            }
        }
        return AjaxResult.success("查询成功",resultMap);
    }

    /**
     * 查询归档申请单列表
     */
    @PostMapping("/getArchiveInfo")
    public TableDataInfo getArchiveInfo(@RequestBody YqdaArchiveForm yqdaArchiveForm, @RequestParam("level") String level, @RequestParam("menuId")  String menuId) throws ArchiveException {
        //String commonColumns = yqdaArchiveFormService.getCommonColumns();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("categoryId",yqdaArchiveForm.getCategoryId());
        jsonObject.put("level",level);
        jsonObject.put("menuId",menuId);
        List<Map<String, String>> getshowfield = tenantCateMdataListService.getshowfield(jsonObject);
        StringBuilder commonColumns = new StringBuilder();
        getshowfield.forEach(item -> commonColumns.append(item.get("FIELD_NAME")).append(","));
        startPage();
        List<Map<String,Object>> list = yqdaArchiveFormService.getArchiveInfo(yqdaArchiveForm,commonColumns.toString(),level);
        return getDataTable(list);
    }

    /**
     * 导出归档申请单列表
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:export')")
    @Log(title = "归档申请单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqdaArchiveForm yqdaArchiveForm)
    {
        List<YqdaArchiveForm> list = yqdaArchiveFormService.selectYqdaArchiveFormList(yqdaArchiveForm);
        ExcelUtil<YqdaArchiveForm> util = new ExcelUtil<YqdaArchiveForm>(YqdaArchiveForm.class);
        util.exportExcel(response, list, "归档申请单数据");
    }

    /**
     * 获取归档申请单详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:query')")
    @GetMapping(value = "/{formId}")
    public AjaxResult getInfo(@PathVariable("formId") String formId)
    {
        return success(yqdaArchiveFormService.selectYqdaArchiveFormByFormId(formId));
    }

    /**
     * 新增归档申请单
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:add')")
    @Log(title = "归档申请单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqdaArchiveForm yqdaArchiveForm)
    {
        return toAjax(yqdaArchiveFormService.insertYqdaArchiveForm(yqdaArchiveForm));
    }

    /**
     * 新增归档申请单
     */
    //@PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:add')")
    @Log(title = "归档申请单", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsert")
    public AjaxResult batchInsertYqdaArchiveForm(@RequestBody List<YqdaArchiveForm> yqdaArchiveForms) {
        String batchNo = String.valueOf(SnowflakeIdGenerator.generateId());
        StringBuilder ids = new StringBuilder();
        String userId = String.valueOf(SecurityUtils.getUserId());
        yqdaArchiveForms.forEach(form -> {
            form.setFormId(String.valueOf(SnowflakeIdGenerator.generateId()));
            //form.setFormNo(batchNo);
            form.setTenantCode(SecurityUtils.getTenantCode());
            form.setUserId(userId);
            ids.append(form.getArchiveId()).append(",");
        });
        if (yqdaArchiveFormService.checkArchiveIsAddForm(yqdaArchiveForms)){
            return AjaxResult.error("已经添加到归档审批单的数据不能再次添加");
        }
        if (yqdaArchiveFormService.checkArchiveUserCategoryForm(yqdaArchiveForms)){
            return AjaxResult.error("归档审批单中已有其它门类的档案数据，请先提交再添加本门类数据");
        }

        YqdaArchiveForm yqdaArchiveForm = yqdaArchiveForms.get(0);
        String subTableName = yqdaArchiveForm.getSubTableName();
        String daType = yqdaArchiveForm.getDaType();
        Long categoryId = yqdaArchiveForm.getCategoryId();
        String idss = ids.toString();
        String msg = "";
        //检查卷内以及项目内是否有数据
        Map<String, List<String>> idWhichHasData = null;
        //TODO 暂时去掉空卷验证
        if("X".equals(daType) || "V".equals(daType)){
            idWhichHasData = yqdaArchiveFormServiceImpl.getIdWhichHasData(idss, daType, categoryId);
            //if(idWhichHasData.size()==0){
            //    if("X".equals(daType)) msg += "项目中无案卷或案卷中无卷内件不能添加到申请单，";
            //    if("V".equals(daType)) msg += "案卷中无卷内件不能添加到申请单，";
            //}else{
            if(idWhichHasData!=null){
                Set<Map.Entry<String, List<String>>> entries = idWhichHasData.entrySet();
                Iterator<Map.Entry<String, List<String>>> iterator = entries.iterator();
                String tempStr = "";
                while(iterator.hasNext()){
                    Map.Entry<String, List<String>> next = iterator.next();
                    String key = next.getKey();
                    List<String> value = next.getValue();
                    if("X".equals(daType)){
                        for(int i=0;i<value.size();i++){
                            tempStr+=value.get(i)+",";
                        }
                    }
                    if("V".equals(daType)){
                        tempStr+=key+",";
                    }
                }
                idss = tempStr;
            }
            //}
            /*for(int i=0;i<yqdaArchiveForms.size();i++){
                String archiveId = yqdaArchiveForms.get(i).getArchiveId();
                if(!idWhichHasData.containsKey(archiveId)){
                    yqdaArchiveForms.remove(i);
                    i--;
                }
            }*/
        }

        //检查是否生成档号
        if(yqdaArchiveForms.size()!=0){
            if(idss.endsWith(",")) idss = idss.substring(0,idss.length()-1);
            if("X".equals(daType)){  //项目层校验卷。。。
                TenantCategory tenantCategory = iTenantCategoryService.selectTenanCategoryByID(categoryId);
                Map<String, String> map = wenjianzhengliService.checkIsExistDh(String.valueOf(categoryId), "F".equals(daType) ? 0 : 1, tenantCategory.getFolderTableName(), idss);
                List<String> list = new ArrayList<>();  //需要除去的项目id集合
                if(idWhichHasData!=null){
                    Set<Map.Entry<String, List<String>>> entries = idWhichHasData.entrySet();
                    Iterator<Map.Entry<String, List<String>>> iterator = entries.iterator();
                    while (iterator.hasNext()){
                        Map.Entry<String, List<String>> next = iterator.next();
                        String key = next.getKey();   //项目id
                        List<String> value = next.getValue();  //项目内卷的id
                        Set<String> kset = map.keySet();    //没有档号的 案卷的id
                        Iterator<String> iterator1 = kset.iterator();
                        while (iterator1.hasNext()){
                            String next1 = iterator1.next();
                            if(value.contains(next1)){
                                list.add(key);
                            }
                        }
                    }
                }
                for(int i=0;i<yqdaArchiveForms.size();i++){
                    String archiveId = yqdaArchiveForms.get(i).getArchiveId();
                    if(list.contains(archiveId)){
                        yqdaArchiveForms.remove(i);
                        i--;
                    }
                }
                if(map.size()!=0 && map.size()!=yqdaArchiveForms.size()) msg += "未生成档号的不能添加到申请单，";
            }else{
                Map<String, String> map = wenjianzhengliService.checkIsExistDh(String.valueOf(categoryId), "F".equals(daType) ? 0 : 1, subTableName, idss);
                for(int i=0;i<yqdaArchiveForms.size();i++){
                    String archiveId = yqdaArchiveForms.get(i).getArchiveId();
                    if(map.containsKey(archiveId)){
                        yqdaArchiveForms.remove(i);
                        i--;
                    }
                }
                if(map.size()!=0 && map.size()!=yqdaArchiveForms.size()) msg += "未生成档号的不能添加到申请单，";
            }
        }


        int result = 0;
        if(yqdaArchiveForms.size()!=0){
            result = yqdaArchiveFormService.batchInsertYqdaArchiveForm(yqdaArchiveForms);
            if (result>0){
                int i = yqdaArchiveFormService.updateYqArchiveState(yqdaArchiveForms,4);
            }
        }
        if(!"".equals(msg)) {
            if(msg.endsWith("，")) msg = msg.substring(0,msg.length()-1);
            return AjaxResult.error(msg);
        }else{
            return toAjax(result);
        }
    }

    /**
     * 修改归档申请单
     */
    //@PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:edit')")
    @Log(title = "归档申请单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqdaArchiveForm yqdaArchiveForm)
    {
        return toAjax(yqdaArchiveFormService.updateYqdaArchiveForm(yqdaArchiveForm));
    }

    /**
     * 删除归档申请单
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:remove')")
    @Log(title = "归档申请单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{archiveIds}")
    public AjaxResult remove(@PathVariable String[] archiveIds)
    {
        List<YqdaArchiveForm> yqdaArchiveForms = yqdaArchiveFormService.selectYqdaArchiveFormsByArchiveIds(archiveIds);
        yqdaArchiveFormService.updateYqArchiveState(yqdaArchiveForms,2);
        return toAjax(yqdaArchiveFormService.deleteYqdaArchiveFormByArchiveIdsAndUserId(archiveIds,SecurityUtils.getUserId()));
    }

    /**
     * 删除归档申请单
     */
    @PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:submit')")
    //@Log(title = "提交归档申请单", businessType = BusinessType.DELETE)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody YqdaArchiveForm yqdaArchiveForm)
    {

        String tenantCode = SecurityUtils.getTenantCode();
        YqdaArchiveForm queryWarpper = new YqdaArchiveForm();
        queryWarpper.setState("0");
        queryWarpper.setUserId(String.valueOf(SecurityUtils.getUserId()));
        String formNo = String.valueOf(SnowflakeIdGenerator.generateId());
        List<YqdaArchiveForm> yqdaArchiveForms = yqdaArchiveFormService.selectYqdaArchiveFormList(queryWarpper);
        if (yqdaArchiveForms.size()==0) return AjaxResult.error("归档申请单中没有数据");
        List<Map<String,Object>> archiveList = yqdaArchiveFormService.getArchiveListByArchiveFormList(yqdaArchiveForms);
        yqdaArchiveForm.setREMARK(yqdaArchiveForm.getRemark());

        //TODO 根据流程查询绑定表单
        R<String> formCode = remoteActivitiService.getFormCodeByBusinessKey("WS_Archive_Save",tenantCode);
        Map<String,Map<String, Object>> archiveListSplit = splitArchiveList.splitArchiveByFormCodeNew(formCode.getData(), archiveList);
        // FIXME 添加测试数据 记得删除
        /*archiveListSplit = new ArrayList<>();
        Map<String, Object> testData1 = createTestData(1);
        archiveListSplit.add(testData1);

        Map<String, Object> testData2 = createTestData(2);
        archiveListSplit.add(testData2);*/
        int size = archiveListSplit.size();
        int count = 0;
        List<String> taskIds = new ArrayList<>();
        for (Map.Entry<String, Map<String, Object>> entry:archiveListSplit.entrySet()) {
            Map<String, Object> varables = entry.getValue();
            if (entry.getKey().equals("notConditionValue")){
                count++;
                continue;
            }
            //remoteActivitiService.startProcessWsArchiveSave(varables);
            List<Map<String,Object>> archiveData = (List<Map<String,Object>>)varables.get("archiveData");
            if(archiveData == null){
                count++;
                continue;
            }
            StringBuilder archiveIds = new StringBuilder();
            archiveData.forEach(item->archiveIds.append(item.get("ID")).append(","));
            if ("".equals(archiveIds.toString())){
                count++;
                continue;
            }
            archiveIds.deleteCharAt(archiveIds.length()-1);
            System.out.println(varables.toString());
            varables.put("processVariables",yqdaArchiveForm.toProcessMap());
            //TODO 测试用参数
            varables.put("archive_type","lt");
            varables.put("archive_has_mj","1");
            R<ActivitiPackage> activitiPackageR = remoteActivitiService.submitProcessWsArchiveSave(varables);
            ActivitiPackage activitiPackage = activitiPackageR.getData();
            ProcessInstance processInstance = activitiPackage.getProcessInstance();
            String processInstanceId = processInstance.getId();
            String bussinessKey = activitiPackage.getBussinessKey();
            yqdaArchiveForm.setArchiveId(archiveIds.toString());
            yqdaArchiveForm.setWorkflowFormId(bussinessKey);
            yqdaArchiveForm.setWorkflowId(processInstanceId);
            //yqdaArchiveForm.setSubmitUserId(String.valueOf(SecurityUtils.getUserId()));
            yqdaArchiveForm.setState("5");
            yqdaArchiveForm.setSplitNo(String.valueOf(SnowflakeIdGenerator.generateId()));
            yqdaArchiveForm.setFormNo(formNo);
            int is = yqdaArchiveFormService.batchUpdateByArchiveIds(yqdaArchiveForm);
            R<String> taskIdByProcessId = remoteActivitiService.getTaskIdByProcessId(processInstanceId);
            if (taskIdByProcessId.getData()!=null){
                taskIds.add(taskIdByProcessId.getData());
            }

        }
        return AjaxResult.success("您的申请单已经根据审批流程被分为"+(size-count)+"份申请提交",taskIds);
    }

    // 创建测试数据
    private static Map<String, Object> createTestData(int id) {
        Map<String, Object> data = new HashMap<>();
        data.put("MJ", 10L);
        data.put("STATE", 2L );

        List<Map<String, Object>> archiveDataList = new ArrayList<>();
        Map<String, Object> archiveData1 = new HashMap<>();
        archiveData1.put("MJ", "Inner MJ value 1 for " + id);
        archiveData1.put("STATE", "Inner STATE value 1 for " + id);
        archiveData1.put("ID", "1263456" + id);
        archiveDataList.add(archiveData1);

        Map<String, Object> archiveData2 = new HashMap<>();
        archiveData2.put("MJ", "Inner MJ value 2 for " + id);
        archiveData2.put("STATE", "Inner STATE value 2 for " + id);
        archiveData2.put("ID", "1263456" + id) ;
        archiveDataList.add(archiveData2);

        data.put("archiveData", archiveDataList);
        return data;
    }

    //@PreAuthorize("@ss.hasPermi('archive:fileCollection:archiveApproval:applicationForm:download")
    //@Log(title = "提交归档申请单", businessType = BusinessType.DELETE)
    @PostMapping("/getArchiveSaveDownloadTitle")
    public void getArchiveSaveDownloadTitle(@RequestParam("categoryId") Long categoryId,@RequestParam("archiveIds") Long[] archiveIds,@RequestParam("daType") String daType,HttpServletResponse response) throws IOException {
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();

        Map<String, Object> archiveSaveDownloadTitle = yqdaArchiveFormService.getArchiveSaveDownloadTitle(categoryId, archiveIds, daType);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;filename=归档档案数据.xlsx");
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(response.getOutputStream());

        // 设置 sheet 名称
        ExcelWriterSheetBuilder sheetBuilder = excelWriterBuilder.sheet("Sheet1");
        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);

        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");
        Set<String> dictSet = new HashSet<>();
        tenantMdataLists.forEach(item->{
            if ("F".equals(daType)&&item.getType().equals(0)&&item.getShowType().equals(5)){
                dictSet.add(item.getFieldName());
            }else if ("V".equals(daType)&&item.getType().equals(1)&&item.getShowType().equals(5)){
                dictSet.add(item.getFieldName());
            }else if ("X".equals(daType)&&item.getType().equals(3)&&item.getShowType().equals(5)){
                dictSet.add(item.getFieldName());
            }
        });
        // 设置表头
        Map<String,Object> titleMap = (Map<String, Object>) archiveSaveDownloadTitle.get("title");
        List<List<String>> head = new ArrayList<>();
        List<String> orderList = new ArrayList<>();

        for (Map.Entry<String,Object> entry:titleMap.entrySet()){
            List<String> list = new ArrayList<>();
            if (entry.getValue()!=null){
                list.add(String.valueOf(entry.getValue()));
                orderList.add(String.valueOf(entry.getKey()));
            }
            head.add(list);
        }

        // 写入表头
        sheetBuilder.head(head);

        // 准备数据
        List<List<Object>> data = new ArrayList<>();
        // 假设你的数据存储在 dataMap 中
        List<HashMap<String, Object>> dataMap = fetchData(archiveSaveDownloadTitle); // 这里是你的数据源

        // 遍历 dataMap，将数据写入 data 列表
        for (HashMap<String,Object> row : dataMap) {
            //List<String> rowData = new ArrayList<>();
            List<Object> valuesList = orderList.stream()
                    .map(row::get) // 从row中获取值
                    .collect(Collectors.toList());
            data.add(valuesList);
        }


        // 写入数据
        sheetBuilder.doWrite(data);

        // 关闭 ExcelWriter
        excelWriterBuilder.autoCloseStream(true);

    }

    // 模拟从你的数据源获取数据
    private static List<HashMap<String, Object>> fetchData(Map<String, Object> map) {
        // 这里模拟数据获取过程，你需要根据你的数据源来获取数据
        return (List<HashMap<String, Object>>) map.get("data");
    }

    /**
     * downloadWaxPaperDocx
     */
    @Log(title = "archiveBorrow", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadArchiveTable")
    public AjaxResult downloadArchiveBorrowTable(@RequestBody YqdaArchiveForm yqdaArchiveForm)throws IOException {
        Date startTime = yqdaArchiveForm.getSubmitTime();
        String borrowDate = "    年  月  日";
        if (startTime!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            borrowDate = calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日";
        }
        String deptName = yqdaArchiveForm.getSubmitDept();
        String username = yqdaArchiveForm.getSubmitUser();
        AjaxResult archiveList = getArchiveList(new YqdaArchiveForm());
        List<Map<String,Object>> archiveListData = (List<Map<String, Object>>) archiveList.get("data");
        if (archiveListData!=null&&archiveListData.size()!=0){
            String daType = String.valueOf(archiveListData.get(0).get("DA_TYPE"));
            String categoryId = String.valueOf(archiveListData.get(0).get("CATEGORY_ID"));
            if ("X".equals(daType)){

            }else if ("V".equals(daType)){

            }else if ("F".equals(daType)){

            }
        }
        StringBuilder archiveNames = new StringBuilder();
        archiveNames.append("测试项目名");
        StringBuilder archiveCodes = new StringBuilder();
        archiveCodes.append("[{\"title\":\"test1\"},{\"title\":\"test2\"},{\"title\":\"test3\"},]");


        JSONObject jsonObject = new JSONObject();
        String type = yqdaArchiveForm.getCategoryIdaf();
        jsonObject.put("menuId","5178");
        jsonObject.put("categoryId","1");
        if ("kj".equals(type)){
            jsonObject.put("type","KY");
        }else if ("sj".equals(type)){
            jsonObject.put("type","SJ");
        }else if ("zp".equals(type)){
            jsonObject.put("type","ZP");
        }
        StringBuilder dataBuilder = new StringBuilder();
        dataBuilder.append("{\"data\":[");
        dataBuilder.append("{\"submitDate\":\"").append(borrowDate).append("\",");              //借阅日期
        dataBuilder.append("\"submitDept\":\"").append(deptName).append("\",");                  //借阅部门
        dataBuilder.append("\"submitUserName\":\"").append(username).append("\",");           //借阅人姓名         //借阅人姓名
        dataBuilder.append("\"submitArchiveName\":\"").append(archiveNames.toString()).append("\","); //借阅档案名称
        dataBuilder.append("\"submitArchiveTitles\":").append("\"testq\"").append("}");  //借阅档案档号
        dataBuilder.append("]}");
        //dataBuilder.deleteCharAt(dataBuilder.length()-1);
        jsonObject.put("data",dataBuilder.toString());
        Map geturl = reportService.geturl(jsonObject);
        return success(geturl);
    }

    /**
     * downloadWaxPaperDocx
     */
    @Log(title = "downloadArchiveTableNew", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/downloadArchiveTableNew")
    public AjaxResult downloadArchiveTableNew(@RequestBody YqdaArchiveYijiaoEntity yqdaArchiveYijiaoEntity)throws IOException {
        Date startTime = new Date(System.currentTimeMillis());
        String borrowDate = "    年  月  日";
        if (startTime!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            borrowDate = calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日";
        }
        String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
        String username = SecurityUtils.getUsername();
        Long categoryId = yqdaArchiveYijiaoEntity.getCategoryId();
        String subTableName = yqdaArchiveYijiaoEntity.getSubTableName();
        List<Map<String, Object>> archiveList = yqdaArchiveFormService.getArchiveListByCategoryAndIds(yqdaArchiveYijiaoEntity.getArchiveIds(), categoryId, "F");
        StringBuilder archiveNames = new StringBuilder();
        archiveNames.append("测试项目名");
        StringBuilder archiveCodes = new StringBuilder();
        archiveCodes.append("[{\"title\":\"test1\"},{\"title\":\"test2\"},{\"title\":\"test3\"},]");


        JSONObject jsonObject = new JSONObject();
        //String type = yqdaArchiveYijiaoEntity.getCategoryIdaf();
        jsonObject.put("menuId","5230");
        jsonObject.put("categoryId","1");
        jsonObject.put("type","KY");
        /*if ("kj".equals(type)){
            jsonObject.put("type","KY");
        }else if ("sj".equals(type)){
            jsonObject.put("type","SJ");
        }else if ("zp".equals(type)){
            jsonObject.put("type","ZP");
        }*/
        StringBuilder dataBuilder = new StringBuilder();
        dataBuilder.append("{\"data\":[");
        for (Map<String, Object> item:archiveList) {
            dataBuilder.append("{\"archiveTitles\":\"").append(item.get("TITLE")).append("\",");       //文件标题
            dataBuilder.append("\"textCopy\":\"").append("").append("\",");                   //文字本数
            dataBuilder.append("\"textPart\":\"").append("").append("\",");                   //文件份数
            dataBuilder.append("\"drawingSheet\":\"").append("").append("\",");           //图纸张数
            dataBuilder.append("\"drawingPart\":\"").append("").append("\",");           //图纸份数
            dataBuilder.append("\"draftCopy\":\"").append("").append("\",");           //底稿本数
            dataBuilder.append("\"underlay\":\"").append("").append("\",");           //底图
            dataBuilder.append("\"remark\":\"").append(item.get("BZ")==null?"":item.get("BZ")).append("\"},");           //备注
        }
        dataBuilder.deleteCharAt(dataBuilder.length()-1);
        dataBuilder.append("]}");
        //dataBuilder.deleteCharAt(dataBuilder.length()-1);
        jsonObject.put("data",dataBuilder.toString());
        Map geturl = reportService.geturl(jsonObject);
        return success(geturl);
    }


}
